package com.gl.admin.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.gl.admin.entity.SysUser;
import com.gl.admin.service.SysUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * jwt 工具类
 */
@Component
public class TokenUtils {

    private static SysUserService staticSysUserService;

    @Resource
    private SysUserService sysUserService;

    @PostConstruct
    public void setUserService() {
        staticSysUserService = sysUserService;
    }

    /**
     * 生成token
     * @param userId 用户名
     * @param password 用户密码
     * @return
     */
    public static String genToken(String userId,String password) {
        return JWT.create().withAudience(userId)
                .withExpiresAt(DateUtil.offsetHour(new Date(),168)) //一周后token过期
                .sign(Algorithm.HMAC256(password));
    }

    /**
     * 获取当前登录的用户信息
     * @return user对象
     */
    public static SysUser getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticSysUserService.getById(userId);
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }


}

